<?php

namespace app\admin\controller;

use app\admin\controller\CommonController;
use app\admin\model\Flink;
use app\util\Util;

/*
 * 友情链接
 */
class FlinkController extends CommonController
{
    /*
     * 友情链接列表
     */
    public function index()
    {
        $list = Flink::order('add_time asc')->paginate(15);

        return view('index', [
            'list' => $list
        ]);
    }

    /*
     * 添加友情链接
     */
    public function add()
    {
        return view('add');
    }

    /*
     * 写入友情链接
     */
    public function postInsert()
    {
        $webname = input('post.webname');
        $url = input('post.url');

        $exist = Flink::where('webname', '=', $webname)->find();
        if (!is_null($exist)) {
            return Util::ajaxReturn(0, '友情链接已存在', null);
        }

        $data = [
            'webname' => $webname,
            'url' => $url,
            'add_time' => time(),
        ];

        $result = Flink::insert($data);
        if ($result) {
            return Util::ajaxReturn(1, '添加成功', null);
        } else {
            return Util::ajaxReturn(0, '添加失败', null);
        }
    }

    /*
     * 编辑友情链接
     */
    public function edit()
    {
        $id = input('param.id');

        $row = Flink::where('id', '=', $id)->find();
        return view('edit', [
            'id' => $id,
            'row' => $row
        ]);
    }

    /*
     * 保存友情链接
     */
    public function postSave()
    {
        $id = input('post.id');
        $webname = input('post.webname');
        $url = input('post.url');

        $exist = Flink::where('webname', '=', $webname)
            ->where('id', '<>', $id)
            ->find();
        if (!is_null($exist)) {
            return Util::ajaxReturn(0, '友情链接已存在', null);
        }

        $data = [
            'webname' => $webname,
            'url' => $url
        ];

        $result = Flink::where('id', '=', $id)->update($data);
        if ($result) {
            return Util::ajaxReturn(1, '修改成功', null);
        } else {
            return Util::ajaxReturn(0, '修改失败', null);
        }
    }

    /*
     * 删除友情链接
     */
    public function del()
    {
        $id = input('param.id');

        $result = Flink::where('id', '=', $id)->delete();
        if ($result) {
            return Util::ajaxReturn(1, '删除成功', null);
        } else {
            return Util::ajaxReturn(0, '删除失败', null);
        }
    }

}